package app.project.directionlensproject.fragment;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import app.project.directionlensproject.HomeActivity;
import app.project.directionlensproject.ListPlaceActivity;
import app.project.directionlensproject.MyApplication;
import app.project.directionlensproject.R;
import app.project.directionlensproject.adapter.CategoryAdapter;
import app.project.directionlensproject.map.MapActivity;
import app.project.directionlensproject.model.Category;
import app.project.directionlensproject.serverapi.ServerAPI;
import app.project.directionlensproject.util.AsyncTask;
import app.project.directionlensproject.util.BundleKeys;
import app.project.directionlensproject.util.Constants;
import app.project.directionlensproject.util.GetDataTask;
import app.project.directionlensproject.util.IGetDataTask;

public class FgCategory extends Fragment implements OnItemClickListener {
	CategoryAdapter adapter;
	GridView grdView;
	public static ArrayList<Category> items;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		grdView = (GridView) inflater.inflate(R.layout.fg_category, container, false);
		// adapter = new CategoryAdapter(getActivity());
		// grdView.setAdapter(adapter);
		initData();
		grdView.setOnItemClickListener(this);

		return grdView;
	}

	public void initData() {
		if (items != null){
			adapter = new CategoryAdapter(getActivity(), items);
			grdView.setAdapter(adapter);
			return;
		}
		new GetDataTask(getActivity(), new IGetDataTask() {
			@Override
			public void onPostExecute(boolean result) throws Exception {
				super.onPostExecute(result);
				adapter = new CategoryAdapter(getActivity(), items);
				grdView.setAdapter(adapter);
			}

			@Override
			public boolean doInBackGround() throws Exception {
				items = ServerAPI.GetAllCatogery();
				return false;
			}
		}, true).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		Category category = adapter.getItem(position);
		Intent i = new Intent(getActivity(), MapActivity.class);
		i.putExtra(BundleKeys.PREV_PAGE, Constants.FROM_CATEGORY);
		i.putExtra(BundleKeys.CATE_ID, category.categoryId);
		MyApplication.isListForAll=true;
		HomeActivity.isListAll=true;
		ListPlaceActivity.listCurrentPlace = null;
		FgListPlace.listCachePlace = null;
		startActivity(i);
	}

}
